/* 移动端导航功能实现 */

class MobileNav {
  constructor() {
    // 配置项
    this.config = {
      breakpoint: 768,
      animationDuration: 300
    };
    
    // 存储元素引用
    this.elements = {
      toggles: [], // 修改为数组，存储所有切换按钮
      nav: null,
      overlay: null,
      dropdownToggles: [],
      currentPage: ''
    };
    
    // 状态管理
    this.isOpen = false;
    this.isMobile = false;
  }
  
  // 初始化导航
  init(basePath = '../') {
    console.log('初始化移动端导航');
    
    // 获取DOM元素
    this._getDOMElements();
    
    // 验证DOM元素
    if (!this._validateDOMElements()) {
      console.warn('移动端导航初始化失败：未找到必要的DOM元素');
      return;
    }
    
    // 检测当前设备和页面
    this._detectDevice();
    this._detectCurrentPage(basePath);
    
    // 绑定完整事件
    this._bindEvents();
    
    // 更新活动状态
    this._updateActiveState();
  }
  
  // 获取DOM元素
  _getDOMElements() {
    this.elements.toggles = Array.from(document.querySelectorAll('.mobile-nav-toggle')); // 获取所有切换按钮
    this.elements.nav = document.querySelector('.mobile-nav');
    this.elements.overlay = document.querySelector('.mobile-nav-overlay');
    this.elements.dropdownToggles = Array.from(document.querySelectorAll('.mobile-dropdown-toggle'));
  }
  
  // 验证DOM元素
  _validateDOMElements() {
    return this.elements.toggles.length > 0 && this.elements.nav && this.elements.overlay;
  }
  
  // 检测设备类型
  _detectDevice() {
    this.isMobile = window.innerWidth <= this.config.breakpoint;
  }
  
  // 检测当前页面
  _detectCurrentPage(basePath) {
    const currentPath = window.location.pathname;
    const pages = [
      { path: 'index.html', id: 'home' },
      { path: 'pages/products.html', id: 'products' },
      { path: 'pages/news.html', id: 'news' },
      { path: 'pages/about.html', id: 'about' },
      { path: 'pages/contact.html', id: 'contact' },
      { path: 'pages/product1.html', id: 'product1' },
      { path: 'pages/product2.html', id: 'product2' },
      { path: 'pages/product3.html', id: 'product3' },
      { path: 'pages/product4.html', id: 'product4' }
    ];
    
    for (const page of pages) {
      const fullPath = basePath + page.path;
      if (currentPath.includes(page.path) || currentPath.includes(fullPath)) {
        this.elements.currentPage = page.id;
        break;
      }
    }
  }
  
  // 绑定事件监听
  _bindEvents() {
    // 为所有切换按钮绑定点击事件
    this.elements.toggles.forEach(toggle => {
      toggle.addEventListener('click', this._toggleNav.bind(this));
    });
    
    // 遮罩点击事件
    this.elements.overlay.addEventListener('click', this._closeNav.bind(this));
    
    // 下拉菜单切换事件
    this.elements.dropdownToggles.forEach(toggle => {
      toggle.addEventListener('click', this._toggleDropdown.bind(this));
    });
    
    // 窗口大小变化事件
    window.addEventListener('resize', this._handleResize.bind(this));
    
    // ESC键关闭导航
    document.addEventListener('keydown', this._handleKeyDown.bind(this));
  }
  
  // 展开所有下拉菜单
  _expandAllDropdowns() {
    this.elements.dropdownToggles.forEach(toggle => {
      toggle.classList.add('active');
      toggle.style.pointerEvents = 'none'; // 禁用点击
      
      const menu = toggle.nextElementSibling;
      if (menu && menu.classList.contains('mobile-dropdown-menu')) {
        menu.classList.add('active');
      }
    });
  }
  
  // 切换导航菜单
  _toggleNav() {
    this.isOpen = !this.isOpen;
    
    if (this.isOpen) {
      this._openNav();
      // 确保下拉菜单展开
      this._expandAllDropdowns();
    } else {
      this._closeNav();
    }
  }
  
  // 打开导航菜单
  _openNav() {
    // 为所有按钮添加active类
    this.elements.toggles.forEach(toggle => {
      toggle.classList.add('active');
    });
    this.elements.nav.classList.add('active');
    this.elements.overlay.classList.add('active');
    document.body.style.overflow = 'hidden'; // 防止背景滚动
  }
  
  // 关闭导航菜单
  _closeNav() {
    // 为所有按钮移除active类
    this.elements.toggles.forEach(toggle => {
      toggle.classList.remove('active');
    });
    this.elements.nav.classList.remove('active');
    this.elements.overlay.classList.remove('active');
    document.body.style.overflow = ''; // 恢复背景滚动
  }
  
  // 切换下拉菜单（禁用）
  _toggleDropdown(e) {
    // 在全部展开模式下，不执行切换操作
    e.stopPropagation();
  }
  
  // 更新活动状态
  _updateActiveState() {
    if (!this.elements.currentPage) return;
    
    // 查找并高亮当前页面的导航项
    const navLinks = document.querySelectorAll('.mobile-nav-link');
    navLinks.forEach(link => {
      if (link.getAttribute('href') && 
          (link.getAttribute('href').includes(this.elements.currentPage) || 
           link.getAttribute('href').includes(this.elements.currentPage.replace('product', 'products')))) {
        link.classList.add('active');
      }
    });
    
    // 对于产品详情页，也高亮产品服务主菜单
    if (this.elements.currentPage.startsWith('product')) {
      const productsLink = document.querySelector('.mobile-nav-link[href*="products.html"]');
      if (productsLink) {
        productsLink.classList.add('active');
        
        // 展开产品服务下拉菜单
        const dropdownToggle = document.querySelector('.mobile-dropdown-toggle');
        const dropdownMenu = document.querySelector('.mobile-dropdown-menu');
        
        if (dropdownToggle && dropdownMenu) {
          dropdownToggle.classList.add('active');
          dropdownMenu.classList.add('active');
        }
      }
    }
  }
  
  // 处理窗口大小变化
  _handleResize() {
    const wasMobile = this.isMobile;
    this._detectDevice();
    
    // 如果从移动端切换到桌面端，关闭导航菜单
    if (wasMobile && !this.isMobile) {
      this._closeNav();
    }
  }
  
  // 处理键盘事件
  _handleKeyDown(e) {
    if (e.key === 'Escape' && this.isOpen) {
      this._closeNav();
    }
  }
}

// 全局初始化函数
window.initMobileNav = function(basePath = '../') {
  const mobileNav = new MobileNav();
  mobileNav.init(basePath);
  
  // 返回API供外部使用
  return {
    toggle: function() {
      mobileNav._toggleNav();
    },
    open: function() {
      if (!mobileNav.isOpen) {
        mobileNav._openNav();
        mobileNav._expandAllDropdowns();
      }
    },
    close: function() {
      if (mobileNav.isOpen) {
        mobileNav._closeNav();
      }
    }
  };
};

// 等待DOM完全加载后初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', function() {
    // 延迟一小段时间，确保DOM已完全加载
    setTimeout(function() {
      // 尝试获取basePath
      try {
        const basePath = window.BASE_PATH || '../';
        window.initMobileNav(basePath);
      } catch (e) {
        console.error('初始化移动端导航时出错:', e);
        // 使用默认路径尝试初始化
        window.initMobileNav('../');
      }
    }, 100);
  });
} else {
  // 如果DOM已加载完成，直接初始化
  setTimeout(function() {
    try {
      const basePath = window.BASE_PATH || '../';
      window.initMobileNav(basePath);
    } catch (e) {
      console.error('初始化移动端导航时出错:', e);
      window.initMobileNav('../');
    }
  }, 100);
}